package com.sample.android.wifi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import android.util.Log;

public class FileOperations
{
	private File	myfile;

	public FileOperations()
	{
	}

	public Boolean write(String fname, String fcontent)
	{
		try
		{
			String fpath = "/sdcard/" + fname + ".txt";
			File file = new File(fpath);
			// If file does not exists, then create it
			if (!file.exists())
			{
				Log.d("Suceess", "Create file Sucess");
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);

			bw.write(fcontent);
			bw.newLine();
			bw.close();
			Log.d("Suceess", "Write file Sucess");
			Log.d("Suceess", file.getPath());
			Log.d("Suceess", file.getCanonicalPath());
			Log.d("Suceess", file.getAbsolutePath());
			myfile = file;
			return true;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}
	}

	public Boolean write(String fname, String[] fcontent, int size)
	{
		try
		{
			String fpath = "/sdcard/" + fname + ".txt";
			File file = new File(fpath);
			// If file does not exists, then create it
			if (!file.exists())
			{
				Log.d("Suceess", "Create file Sucess");
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			for (int i = 0; i < size; ++i)
			{
				bw.write(fcontent[i]);
				bw.newLine();
			}

			bw.close();
			Log.d("Suceess", "Write file Sucess");
			Log.d("Suceess", file.getPath());
			Log.d("Suceess", file.getCanonicalPath());
			Log.d("Suceess", file.getAbsolutePath());
			myfile = file;
			return true;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}
	}

	public String read(String fname)
	{
		BufferedReader br = null;
		String response = null;
		try
		{
			StringBuffer output = new StringBuffer();
			String fpath = "/sdcard/" + fname + ".txt";
			br = new BufferedReader(new FileReader(fpath));
			String line = "";
			while ((line = br.readLine()) != null)
			{
				output.append(line + "\n");
			}
			response = output.toString();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return null;
		}
		return response;
	}

	public File getFile()
	{
		return myfile;
	}

}
